<template>
	<div class="dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" :close-on-click-modal="false" width="1200px">
			<el-form ref="formRef" label-width="auto" :model="state.ruleForm" :rules="state.rules">
				<el-row class="mb20" :gutter="20">
					<el-col :span="12">
						<el-form-item label="公告标题" prop="title">
							<el-input v-model="state.ruleForm.title" placeholder="请输入分类名称" clearable />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="公告时间" prop="notice_time">
							<el-date-picker v-model="state.ruleForm.notice_time" type="datetime" format="YYYY-MM-DD HH:mm:ss" placeholder="请选择公告时间" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row class="mb20" :gutter="20">
					<el-col :span="12" style="align-items: center">
						<el-form-item label="发布权限" prop="type">
							<el-radio-group v-model="state.ruleForm.type">
								<el-radio :value="1">用户等级</el-radio>
								<el-radio :value="2">指定用户</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item v-if="state.ruleForm.type == 1" label="用户等级" prop="authority">
							<el-select multiple v-model="state.ruleForm.authority" clearable placeholder="请选择用户等级">
								<el-option label="粉丝" value="1" />
								<el-option label="铜牌" value="2" />
								<el-option label="银牌" value="3" />
								<el-option label="金牌" value="4" />
							</el-select>
						</el-form-item>
						<el-form-item v-else label="用户昵称" prop="user_id">
							<el-select
								v-model="state.ruleForm.user_id"
								multiple
								filterable
								remote
								clearable
								remote-show-suffix
								:loading="state.userSelect.loading"
								:remote-method="remoteUserSelect"
								placeholder="请输入用户昵称/请选择用户"
							>
								<el-option
									v-for="item in state.userSelect.options"
									:key="item.id"
									:label="item.nickname + '—' + item.mobile + ' ' + formatterIdentity(item.identity)"
									:value="item.id"
								/>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row class="mb20" :gutter="20">
					<el-col :span="24">
						<el-form-item label="通知内容" prop="content">
							<div style="border: 1px solid #ccc">
								<Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
								<Editor
									style="height: 500px; overflow-y: hidden"
									v-model="state.ruleForm.content"
									:defaultConfig="editorConfig"
									:mode="mode"
									@onCreated="handleCreated"
								/>
							</div>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<el-button @click="onCancel" size="default">取 消</el-button>
				<el-button type="primary" @click="onSubmit" :loading="state.dialog.submitLoading" size="default">提 交</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { IToolbarConfig } from '@wangeditor/editor';
import { ElMessage } from 'element-plus';
import { nextTick, reactive, ref, shallowRef, onBeforeUnmount, inject } from 'vue';
import { announcementApi, usersApi } from '/@/api';
import { formatterIdentity, randomString } from '/@/utils/utils';
import upload from '/@/utils/uploadCos';
const Dayjs: any = inject('dayjs');

const UsersApi = usersApi();
const AnnouncementApi = announcementApi();

// 编辑器实例
const editorRef = shallowRef();
// 内容 HTML
const toolbarConfig: Partial<IToolbarConfig> = {};
// const editor = createEditor({})
// console.log(editor.getAllMenuKeys())
// console.log('toolbarConfig: ', toolbarConfig)
toolbarConfig.excludeKeys = ['insertVideo', 'uploadVideo', 'editVideoSize'];
const editorConfig: any = {
	placeholder: '请输入内容...',
	MENU_CONF: {},
};
editorConfig.MENU_CONF['uploadImage'] = {
	server: '/api/upload',
	onBeforeUpload(file: File) {
		return file;
	},
	// 自定义上传
	async customUpload(file: File, insertFn: any) {
		let fileExtension = file.name.substring(file.name.lastIndexOf('.') + 1);
		let path = `/seamall/announcement/${Dayjs().year()}/${Dayjs().month()}/${Dayjs().date()}/${randomString(32).toLowerCase()}.${fileExtension}`;
		console.log(file);
		console.log(path);
		upload(file, path)
			.then((res1: any) => {
				console.log('上传成功', res1);
				if (res1.err) {
					ElMessage.error(res1.err.message);
					// const fileFindIndex = state.fileList.findIndex((item: any) => item.uid == 1);
					// state.fileList.splice(fileFindIndex, 1);
					// uploadLoading.value.close();
					// imageUploadRef.value.handleRemove(file);
					// emit('update:modelValue', listToString());
					return;
				}
				insertFn(res1.url, res1.url, res1.url);
				// state.fileList = state.fileList.map((item: any) => {
				// 	if (item.uid == file.uid) {
				// 		return { url: res1.url, upload: true, uid: item.uid };
				// 	}
				// 	return item;
				// });
				// emit('update:modelValue', listToString());
				// uploadLoading.value.close();
			})
			.catch(() => {
				// imageUploadRef.value.handleRemove(file);
				// uploadLoading.value?.close();
				// emit('update:modelValue', listToString());
			});
	},
};
const mode = 'default';
const handleCreated = (editor: any) => {
	editorRef.value = editor; // 记录 editor 实例
};

console.log(editorConfig);

let callback: Function = () => {};
// 定义变量内容
const state = reactive({
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitLoading: false,
	},
	ruleForm: {
		announcement_id: '',
		title: '',
		notice_time: '',
		type: 1,
		authority: [] as any,
		content: '',
		content_en: '',
		content_lo: '',
		user_id: [],
	},
	rules: {
		title: [{ required: true, message: '公告标题不能为空', trigger: ['blur'] }],
		notice_time: [{ required: true, message: '公告时间不能为空', trigger: ['blur','change'] }],
		authority: [{ required: true, message: '用户等级不能为空', trigger: ['blur', 'change'] }],
		user_id: [{ required: true, message: '用户昵称不能为空', trigger: ['blur', 'change'] }],
		content: [{ required: true, message: '通知内容不能为空', trigger: ['blur'] }],
	},
	userSelect: {
		loading: false,
		options: [] as any,
	},
});
const formRef = ref();

/********** 触发事件 **********/
// 取消
const onCancel = () => {
	state.dialog = {
		isShowDialog: false,
		type: '',
		title: '',
		submitLoading: false,
	};
};
// 提交
const onSubmit = () => {
	formRef.value.validate((valid: boolean) => {
		if (!valid) return;
		state.dialog.submitLoading = true
		let params = {
			...state.ruleForm,
			notice_time: Dayjs(state.ruleForm.notice_time).unix(),
			authority1: state.ruleForm.authority.some((item: any) => item == '1'),
			authority2: state.ruleForm.authority.some((item: any) => item == '2'),
			authority3: state.ruleForm.authority.some((item: any) => item == '3'),
			authority4: state.ruleForm.authority.some((item: any) => item == '4'),
			user_id: state.ruleForm.user_id.join(','),
		};
		if (state.dialog.type === 'add') {
			_systemAnnouncementAdd(params);
		} else {
			_systemAnnouncementEdit(params);
		}
	});
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
	const editor = editorRef.value;
	if (editor == null) return;
	editor.destroy();
});

/********** 方法事件 **********/
// 打开
const openDialog = (data: any, row: any, fn: Function) => {
	console.log(row);
	state.dialog = {
		isShowDialog: true,
		type: data.type,
		title: data.title,
		submitLoading: false,
	};
	callback = fn;
	nextTick(() => {
		formRef.value.resetFields();
		state.ruleForm.user_id = [];
		state.ruleForm.authority = [];
		if (data.type == 'edit') {
			state.ruleForm.title = row.title;
			state.ruleForm.notice_time = Dayjs(row.notice_time * 1000).format('YYYY-MM-DD HH:mm:ss');
			state.ruleForm.type = Number(row.type);
			state.ruleForm.content = row.content;
			state.ruleForm.user_id = row.user_info.map((item: any) => {
				return item.id;
			});
			state.ruleForm.announcement_id = row.id;

			for (let index = 1; index < 5; index++) {
				if (row['authority' + index] == 1) {
					state.ruleForm.authority.push(index + '');
				}
			}
		}
		_usersList({});
	});
};
const remoteUserSelect = (query: string) => {
	if (query) {
		console.log('------', query);
		state.userSelect.loading = true;
		_usersList({
			nickname: query,
		});
	}
};
/********** 网络请求 **********/
// 用户列表
const _usersList = (params: Object) => {
	UsersApi.usersList(params)
		.then((res: any) => {
			state.userSelect.options = res.data.list;
			state.userSelect.loading = false;
		})
		.catch(() => (state.userSelect.loading = false));
};
// 添加
const _systemAnnouncementAdd = (params: Object) => {
	AnnouncementApi.systemAnnouncementAdd(params)
		.then(() => {
			ElMessage.success('操作成功！');
			onCancel();
			callback();
		})
		.catch(() => (state.dialog.submitLoading = false));
};
// 编辑
const _systemAnnouncementEdit = (params: Object) => {
	AnnouncementApi.systemAnnouncementEdit(params)
		.then(() => {
			ElMessage.success('操作成功！');
			onCancel();
			callback();
		})
		.catch(() => (state.dialog.submitLoading = false));
};

/********** 方法向父组件暴露 **********/
defineExpose({ openDialog });
</script>

<style scoped lang="scss">
.dialog-container {
	:deep(.el-date-editor) {
		flex: 1;
	}
	:deep(.el-select) {
		flex: 1;
	}
}
</style>
